package com.lagou.edu.zdy.rpc;

import com.lagou.edu.zdy.util.JSONSerializer;
import com.lagou.edu.zdy.util.RpcDecoder;
import com.lagou.edu.zdy.util.RpcEncoder;
import com.lagou.edu.zdy.util.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RpcConsumer {
    //线程池
    private static ExecutorService executor =
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    private static UserClientHandler client;

    /**
     *
     * 创建一个代理对象
     * @param userServiceClass
     * @param request
     * @return
     */
    public Object createProxy(Class<UserService> userServiceClass, RpcRequest request) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[]{userServiceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        if (client ==null) {
                            initClient();
                        }

                        if(args!=null && args.length>0) {
                            request.setParameters(args);
                            Class<?>[] classes = new Class<?>[args.length];
                            int i = 0;
                            for (Object arg : args) {
                                classes[i] = arg.getClass().getClass();
                                i++;
                            }
                            request.setParameterTypes(classes);
                        }

                        client.setPara(request);
                        return executor.submit(client).get();
                    }
                });
    }

    private void initClient() {
        client = new UserClientHandler();
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new StringDecoder());
//                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
//                        pipeline.addLast(new RpcDecoder(String.class, new JSONSerializer()));
                        pipeline.addLast(client);
                    }
                });

        try {
            bootstrap.connect("localhost",8990).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
